﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;

using SoftMedia.Opcion.Web.OpcionService;

namespace SoftMedia.Opcion.Web.Models
{
    #region Models

    public class ChangePasswordModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Contraseña actual")]
        public string OldPassword { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [Display(Name = "Nueva contraseña")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirme nueva contraseña")]
        [Compare("NewPassword", ErrorMessage = "Las nuevas contraseñas no concuerdan")]
        public string ConfirmPassword { get; set; }
    }

    public class ChangeInfoModel
    {
        [DataType(DataType.Text)]
        [Display(Name = "Remitente")]
        public string From { get; set; }

        [DataType(DataType.Text)]
        [Display(Name = "Destinatario")]
        public string To { get; set; }


        [DataType(DataType.Text)]
        [Display(Name = "Asunto")]
        public string Subject { get; set; }

        [DataType(DataType.MultilineText)]
        [Display(Name = "Cuerpo del Mensaje")]
        public string Body { get; set; }

        [Display(Name = "Datos Email")]
        public seguimientoemail SeguimientoEmail { get; set; }
    }

    public class LogOnModel
    {
        [Required]
        [Display(Name = "Usuario")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Contraseña")]
        public string Password { get; set; }

        [Display(Name = "Recordarme")]
        public bool RememberMe { get; set; }
    }

    #endregion

    #region Services
    // The FormsAuthentication type is sealed and contains static members, so it is difficult to
    // unit test code that calls its members. The interface and helper class below demonstrate
    // how to create an abstract wrapper around such a type in order to make the AccountController
    // code unit testable.

    public interface IMembershipService
    {

        ClientesPorDocumento_Result ValidateUser(string userName, string password);
        bool ChangePassword(string userName, string oldPassword, string newPassword);
        bool ChangeInfo(string userName, string oldaddress, string newadress, string oldphonenumber, string newphonenumber, string oldemail, string newemail);
    }

    public class AccountMembershipService : IMembershipService
    {

        public ClientesPorDocumento_Result ValidateUser(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Este campo es obligatorio", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Este campo es obligatorio", "password");

            OpcionService.OpcionClient svc = new OpcionService.OpcionClient();
            var rs = svc.Authentication(userName, password);
            if (rs != null)
                return rs;
            else
                return null;
        }



        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Este campo es obligatorio", "userName");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Este campo es obligatorio", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Este campo es obligatorio", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                OpcionService.OpcionClient svc = new OpcionClient();
                if ('T' == svc.CambioPassword(userName, oldPassword, newPassword))
                    return true;
                else return false;
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        //public bool ChangeInfo(string userName, string oldaddress, string newadress, string oldphonenumber, string newphonenumber, string oldemail, string newemail)
        //{
        //    if (String.IsNullOrEmpty(newadress)) throw new ArgumentException("Este campo es obligatorio", "userName");
        //    if (String.IsNullOrEmpty(newphonenumber)) throw new ArgumentException("Este campo es obligatorio", "oldPassword");
        //    if (String.IsNullOrEmpty(newemail)) throw new ArgumentException("Este campo es obligatorio", "newPassword");

        //    // The underlying ChangePassword() will throw an exception rather
        //    // than return false in certain failure scenarios.
        //    try
        //    {
                


        //        OpcionService.AsociadoModel asoc = new AsociadoModel();
        //        asoc.email = newemail;
        //        asoc.fono = newphonenumber;
        //        asoc.direccion = newadress;

        //        OpcionService.OpcionClient svc = new OpcionClient();

        //        if ('T' == svc.ActualizacionDatosAsociados(userName, asoc))
        //            return true;
        //        else return false;
        //    }
        //    catch (ArgumentException)
        //    {
        //        return false;
        //    }
        //    catch (MembershipPasswordException)
        //    {
        //        return false;
        //    }
        //}


        public bool ChangeInfo(string userName, string oldaddress, string newadress, string oldphonenumber, string newphonenumber, string oldemail, string newemail)
        {
            throw new NotImplementedException();
        }
    }

    public interface IFormsAuthenticationService
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Este campo es obligatorio", "userName");

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
    #endregion

    #region Validation
    public static class AccountValidation
    {
        public static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
    {
        private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
        private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;

        public ValidatePasswordLengthAttribute()
            : base(_defaultErrorMessage)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
                name, _minCharacters);
        }

        public override bool IsValid(object value)
        {
            string valueAsString = value as string;
            return (valueAsString != null && valueAsString.Length >= _minCharacters);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[]{
                new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue)
            };
        }
    }
    #endregion
}